<template>
  <div>
    <!-- 下载按钮 -->
    <a
      href="#"
      @click="down(1)"
      style="display: block; height: 42px !important"
      class="text-white bg-primary-700 hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 font-medium rounded-lg text-sm px-4 lg:px-5 py-2 lg:py-2.5 dark:bg-primary-600 dark:hover:bg-primary-700 focus:outline-none dark:focus:ring-primary-800 btns"
    >
      {{ text1 }}
    </a>

    <!-- 进度条 -->
    <div v-if="showProgress" class="progress-container">
      <div class="progress-bar" :style="{ width: `${progress}%` }"></div>
      <span class="progress-text">{{ progress }}%</span>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import axios from "axios";
import { DemoApi, logStatisticsApi } from "@/api/demo";
import type { AxiosProgressEvent } from "axios";
// 按钮文本和状态
const text1 = ref("免费下载");
const showProgress = ref(false);
const progress = ref(0);

// 下载文件（支持进度监听）
const downFiles = (url: string, fileName: string): Promise<void> => {
  // 标记为已执行
  hasLoggedProgress.value = false;
  hasLoggedComplete.value = false;
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        responseType: "blob", // 重要：告诉axios返回二进制数据
        onDownloadProgress: (progressEvent: AxiosProgressEvent) => {
          if (progressEvent.total) {
            progress.value = Math.round(
              (progressEvent.loaded / progressEvent.total) * 100
            );
            trackDownloadProgress(progress.value, progressEvent);
          }
        },
      })
      .then((response) => {
        // 下载成功
        downloadLog({ type: 2, source: 1 });
        // 创建下载链接并触发下载
        const blobUrl = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = blobUrl;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(blobUrl); // 释放内存
        resolve();
      })
      .catch(reject);
  });
};
const hasLoggedProgress = ref(false);
const hasLoggedComplete = ref(false);
// 示例：下载进度统计（可替换为实际业务逻辑）
const trackDownloadProgress1 = (
  progress: number,
  progressEvent?: ProgressEvent
) => {
  // 标志变量，记录是否已经执行过 progress > 0 && progress < 100 的逻辑

  // type 类型（0：下载， 1：开始下载，2：下载成功，3：下载失败）
  if (progress > 0 && progress < 100) {
    // 示例：调用统计接口
    if (!hasLoggedProgress.value) {
      // 只有未执行过时才调用
      console.log("下载中，触发统计或其他逻辑");
      const params = {
        type: 1,
        source: 1,
      };
      hasLoggedProgress.value = true; // 标记为已执行
      downloadLog(params);
    }
  }
  // if (progress === 100 && !hasLoggedComplete.value) {
  //   hasLoggedComplete.value = true;
  //   // 示例：调用统计接口
  //   const params = {
  //     type: 2,
  //     source: 1,
  //   };
  //   downloadLog(params);
  // }
};
const trackDownloadProgress = (
  progress: number,
  progressEvent?: ProgressEvent
) => {
  if (progressEvent?.total && progressEvent.loaded >= progressEvent.total) {
    if (!hasLoggedComplete.value) {
      hasLoggedComplete.value = true;
      // downloadLog({ type: 2, source: 1 });
    }
  } else if (progress > 0 && progress < 100 && !hasLoggedProgress.value) {
    hasLoggedProgress.value = true;
    downloadLog({ type: 1, source: 1 });
  }
};
// 发起日志请求
const downloadLog = (params) => {
  logStatisticsApi
    .downloadStatisticsLog(params)
    .then((res) => {
      if (res.code === 200) {
        console.log("接口调用成功", res.data);
      } else {
        console.error("接口返回错误:", res.message);
      }
    })
    .catch((error) => {
      console.error("请求失败:", error);
    });
};

// 下载流程
const down = (num: number) => {
  const btnRef = text1; // 当前按钮的ref
  hasLoggedProgress.value = false; // 重置“下载中”标志
  hasLoggedComplete.value = false; // 重置“下载完成”标
  // 1. 下载开始前检查
  if (btnRef.value === "下载中...") return;
  btnRef.value = "下载中...";
  showProgress.value = true;
  progress.value = 0;

  // 示例：触发“下载开始”逻辑（如统计）
  console.log("下载开始");
  // AnalyticsApi.trackEvent('download_start', { fileName: 'example.zip' });

  // 2. 发起请求
  DemoApi.test()
    .then((res) => {
      if (res.code === 200 && res.data?.fileName) {
        const downUrl = "/package/" + res.data.fileName;
        const fileName = res.data.fileName;
        return downFiles(downUrl, fileName);
      } else {
        throw new Error("无效的下载信息");
      }
    })
    .then(() => {
      // 3. 下载完成逻辑
      btnRef.value = "下载完成";
      console.log("下载完成");
      // 示例：触发“下载完成”逻辑（如提示用户）
      // alert("文件下载完成！");
      setTimeout(() => {
        btnRef.value = "免费下载";
        showProgress.value = false;
      }, 1000);
    })
    .catch((err) => {
      // 4. 错误处理
      console.error("下载失败:", err);
      btnRef.value = "免费下载";
      showProgress.value = false;
      const params = {
        type: 3,
        source: 1,
      };
      downloadLog(params);
      alert("下载失败，请重试！");
    });
};
</script>

<style scoped>
.progress-container {
  width: 100%;
  height: 24px;
  background-color: #f0f0f0;
  border-radius: 12px;
  margin-top: 8px;
  overflow: hidden;
  position: relative;
}
.progress-bar {
  height: 100%;
  background-color: #4caf50;
  transition: width 0.3s;
}
.progress-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  color: #333;
}
</style>